from rest_framework import serializers
from .models import RepairRecord, MaintenanceItem, RepairRecordImage


class RepairRecordImageSerializer(serializers.ModelSerializer):
    """维修记录图片序列化器"""
    file_size_human_readable = serializers.ReadOnlyField()
    image_url = serializers.SerializerMethodField()
    
    class Meta:
        model = RepairRecordImage
        fields = [
            'id', 'repair_record', 'image', 'original_filename', 
            'file_size', 'file_size_human_readable', 'description', 
            'upload_time', 'image_url'
        ]
        read_only_fields = ['id', 'upload_time', 'file_size_human_readable']
    
    def get_image_url(self, obj):
        """获取图片URL"""
        if obj.image:
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(obj.image.url)
            return obj.image.url
        return None


class RepairRecordSerializer(serializers.ModelSerializer):
    """设备维修记录单序列化器"""
    images = RepairRecordImageSerializer(many=True, read_only=True)
    
    class Meta:
        model = RepairRecord
        fields = [
            'id', 'record_number', 'system_name', 'equipment_name', 
            'fault_date', 'equipment_number', 'fault_description',
            'maintainer_name', 'contact_phone', 'maintenance_method',
            'replacement_parts', 'completion_date', 'confirmer',
            'attachments', 'create_time', 'update_time', 'images'
        ]
        read_only_fields = ['id', 'create_time', 'update_time', 'images']
    
    def create(self, validated_data):
        """创建维修记录时自动生成记录编号"""
        if not validated_data.get('record_number'):
            # 自动生成记录编号
            from datetime import datetime
            date_str = datetime.now().strftime('%Y%m%d')
            count = RepairRecord.objects.filter(
                record_number__startswith=date_str
            ).count() + 1
            validated_data['record_number'] = f"{date_str}{count:03d}"
        
        return super().create(validated_data)


class MaintenanceItemSerializer(serializers.ModelSerializer):
    months = serializers.DictField(write_only=True, required=False)
    
    class Meta:
        model = MaintenanceItem
        fields = '__all__'
        
    def create(self, validated_data):
        # 处理months字段
        months_data = validated_data.pop('months', {})
        
        # 月份映射
        month_mapping = {
            '1月': 'january', '2月': 'february', '3月': 'march', '4月': 'april',
            '5月': 'may', '6月': 'june', '7月': 'july', '8月': 'august',
            '9月': 'september', '10月': 'october', '11月': 'november', '12月': 'december'
        }
        
        # 将months数据转换为对应的英文字段
        for chinese_month, value in months_data.items():
            english_month = month_mapping.get(chinese_month)
            if english_month:
                validated_data[english_month] = value
        
        # 创建实例
        instance = MaintenanceItem.objects.create(**validated_data)
        return instance
    
    def to_representation(self, instance):
        """序列化时将英文月份字段转换为months字典"""
        data = super().to_representation(instance)
        
        # 月份映射（反向）
        month_mapping = {
            'january': '1月', 'february': '2月', 'march': '3月', 'april': '4月',
            'may': '5月', 'june': '6月', 'july': '7月', 'august': '8月',
            'september': '9月', 'october': '10月', 'november': '11月', 'december': '12月'
        }
        
        # 构建months字典
        months = {}
        for english_month, chinese_month in month_mapping.items():
            months[chinese_month] = data.get(english_month, '')
        
        data['months'] = months
        return data


class RepairRecordListSerializer(serializers.ModelSerializer):
    """维修记录列表序列化器（简化版）"""
    
    class Meta:
        model = RepairRecord
        fields = [
            'id', 'record_number', 'system_name', 'equipment_name',
            'fault_date', 'completion_date', 'create_time'
        ]


class MaintenanceItemListSerializer(serializers.ModelSerializer):
    """维保记录列表序列化器"""
    
    class Meta:
        model = MaintenanceItem
        fields = [
            'id', 'system_name', 'system_category', 'equipment_name',
            'content', 'level', 'cycle',
            'type', 'create_time', 'update_time'
        ]
    
    def to_representation(self, instance):
        """序列化时将英文月份字段转换为months字典"""
        data = super().to_representation(instance)
        
        # 月份映射
        month_mapping = {
            'january': '1月', 'february': '2月', 'march': '3月',
            'april': '4月', 'may': '5月', 'june': '6月',
            'july': '7月', 'august': '8月', 'september': '9月',
            'october': '10月', 'november': '11月', 'december': '12月'
        }
        
        # 构建months字典
        months = {}
        for english_field, chinese_month in month_mapping.items():
            months[chinese_month] = getattr(instance, english_field, '')
        
        data['months'] = months
        return data